package com.bah.tract.security;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.Enumeration;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public final class KeyStoreCreator {

	private KeyStoreCreator() {

	}

	/**
	 * @param args
	 * @throws IOException
	 * @throws GeneralSecurityException
	 */
	public static void main(final String[] args)
			throws GeneralSecurityException, IOException {

		String keystoreFile = "out.jks";
		String storepass = "changeit";

		if (keystoreFile != null && storepass != null) {
			final KeyStore keystore = KeyStore.getInstance("JKS");
			keystore.load(null, null);
			// These are required
			copyEntry(keystore, storepass, "tract",
					"c:/projects/mse/tract.bah.com.p12", "test");
			final OutputStream output = FileUtils.openOutputStream(new File(
					keystoreFile));
			try {
				keystore.store(output, storepass.toCharArray());
			} finally {
				IOUtils.closeQuietly(output);
			}
		}

	}

	private static KeyStore openKeystore(final String file, final String pass)
			throws GeneralSecurityException, IOException {
		final KeyStore source = KeyStore.getInstance("PKCS12");
		final InputStream input = FileUtils.openInputStream(new File(file));
		try {
			source.load(input, pass.toCharArray());
		} finally {
			IOUtils.closeQuietly(input);
		}
		return source;
	}

	private static void copyEntry(final KeyStore keystore,
			final String keystorePass, final String alias,
			final String pkcs12File, final String pkcs12Pass)
			throws GeneralSecurityException, IOException {
		final KeyStore source = openKeystore(pkcs12File, pkcs12Pass);
		final Enumeration<String> enumeration = source.aliases();
		if (enumeration.hasMoreElements()) {
			keystore.setEntry(alias, source.getEntry(enumeration.nextElement(),
					new KeyStore.PasswordProtection(pkcs12Pass.toCharArray())),
					new KeyStore.PasswordProtection(keystorePass.toCharArray()));
		}

	}

}
